extends Node
# res://scripts/player/StateMichine.gd
class_name StateMachine

@export var initial_state: String = "idle"  # 默认初始状态
var current_state: State
var states: Dictionary = {}  # 存储所有状态

func _ready():
	# 自动注册所有子状态（需将状态节点作为StateMachine的子节点）
	for child in get_children():
		if child is State:
			states[child.name.to_lower()] = child
			child.state_machine = self  # 绑定状态机引用

	# 初始化初始状态
	if initial_state in states:
		change_state(initial_state)

# 切换状态
func change_state(new_state: String) -> void:
	if not states.has(new_state) or current_state == states[new_state]:
		return

	# 退出当前状态
	if current_state:
		current_state.exit()

	# 进入新状态
	current_state = states[new_state]
	current_state.enter()

# 每帧更新当前状态
func _process(delta: float):
	if current_state:
		current_state.update(delta)
